﻿namespace TinyAsset
{
    public abstract class BaseLoader<T> : AsyncOperationBase<T> where T : BaseLoader<T>
    {
        public readonly string Key;

        public bool IsCompleted { get; protected set; } = false;

        public int RefCount { get; protected set; } = 0;

        public bool IsRunning { get; protected set; } = false;

        public BaseLoader(string key)
        {
            Key = key;
        }

        protected abstract void SyncLoadHandler();

        public void Load()
        {
            IncrementReferenceCount();
            SyncLoadHandler();
            NotifyCompletion();
        }

        protected abstract void AsyncLoadHandler();

        public void LoadAsync()
        {
            IsDone = false;
            IsRunning = true;
            IncrementReferenceCount();
        }

        public void Update(float deltaTime, float unscaledDeltaTime)
        {
            if (IsRunning)
            {
                AsyncLoadHandler();
                if (IsCompleted)
                    IsRunning = false;
            }
        }

        public abstract void Unload();

        public bool IsAlive()
        {
            return RefCount > 0;
        }

        public void IncrementReferenceCount()
        {
            RefCount++;
        }

        public void DecrementReferenceCount()
        {
            RefCount--;
        }
    }
}